import Icon from '@/components/Icon'
import { useInitState } from '@/hooks/useInitState'
import { getAllChannels, getUserChannels } from '@/store/actions/home'
import { RootAction, RootState } from '@/types/store'
import { Popup, Tabs } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleList from './ArticleList'
import Channels from './Channels'

import styles from './index.module.scss'

const Home = () => {
  // 封装一个函数 返回异步action 请求用户频道
  const userChannels = useInitState(getUserChannels).home.userChannels

  useInitState(getAllChannels)

  const [showPopup, setShowPopup] = useState(false)

  const active = useSelector((state: RootState) => state.home.active)

  const dispatch = useDispatch()

  const history = useHistory()

  useEffect(() => {
    dispatch({
      type: 'home/set_active',
      payload: userChannels[0]?.id,
    } as RootAction)
  }, [dispatch, userChannels])

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      <Tabs
        className="tabs"
        activeLineMode="fixed"
        activeKey={active + ''}
        onChange={(key) => {
          // 切换tab触发
          console.log(key)

          // 更新到仓库中的active
          dispatch({
            type: 'home/set_active',
            payload: +key,
          } as RootAction)
        }}
      >
        {userChannels.map((item) => {
          return (
            <Tabs.Tab title={item.name} key={item.id}>
              <ArticleList channelId={item.id}></ArticleList>
            </Tabs.Tab>
          )
        })}
      </Tabs>

      <div className="tabs-opration">
        <Icon name="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon name="iconbtn_channel" onClick={() => setShowPopup(true)} />
      </div>

      {/* 频道管理的弹层 */}
      <Popup
        visible={showPopup}
        position="left"
        destroyOnClose
        bodyStyle={{ width: '100vw' }}
      >
        <Channels close={() => setShowPopup(false)}></Channels>
      </Popup>
    </div>
  )
}

export default Home
